package com.zkc.zblog.controller;

import com.zkc.zblog.entity.JobForm;
import com.zkc.zblog.entity.ZblogUser;
import com.zkc.zblog.exception.ErrorCode;
import com.zkc.zblog.service.JobService;
import com.zkc.zblog.utils.Dto;
import com.zkc.zblog.utils.DtoUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.SecurityUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;

@RestController
@RequestMapping("/timing")
@Api(description = "定时任务实现接口")
public class QuartzController {

    @Resource
    JobService jobService;

    /**
     * 后台文章定时发布接口
     *
     * */
    @ApiOperation(value = "后台文章定时发布接口", notes = "添加定时发布任务")
    @PostMapping("/add")
    public Dto addJob(@RequestBody JobForm form) {

        ZblogUser zblogUser = (ZblogUser) SecurityUtils.getSubject().getPrincipal();  //获取当前登录用户的个人信息

        Long artuleuser = zblogUser.getYids();     //当前登录作者 与文章的外键

        form.setArtuleuser(artuleuser);

        if (StringUtils.isEmpty(form.getArtuledata())) {//判断文章发布时间是否为空
            form.setArtuledata(new Date());
        }
        if (StringUtils.isEmpty(form.getArticlekeyword())) {//如果关键字为空 直接把标题的内容写入关键字
            form.setArticlekeyword(form.getArticlename());
        }
        if (StringUtils.isEmpty(form.getArticledescription())) {//如果关键字描述 直接把标题的内容写入描述
            form.setArticledescription(form.getArticlename());
        }

        try {
            jobService.addJob(form);
            return DtoUtil.returnSuccess("操作成功");
        } catch (Exception e) {
            return DtoUtil.returnFail(e.getMessage(), ErrorCode.SEARCH_ITRIP_HOTEL_LIST_BY_HOT_CITY_FAIL);
        }

    }

    /**
     *后台文章定时任务的删除接口
     * */
    @ApiOperation(value = "后台文章定时任务的删除接口", notes = "删除定时任务")
    @DeleteMapping("/deleteJob")
    public Dto deleteJob(@RequestBody JobForm form) {

        if (StringUtils.isEmpty(form.getJobClassName())) {
            return DtoUtil.returnSuccess(ErrorCode.DING_SHI_REN_WU_QUAN_LEI_MING_JOBCLASSNAME);
        }
        if (StringUtils.isEmpty(form.getJobGroupName())) {
            return DtoUtil.returnSuccess(ErrorCode.REN_WU_ZU_MING_JOBGROUPNAME);
        }

        try {
            jobService.deleteJob(form);
        } catch (Exception e) {
            return DtoUtil.returnSuccess(ErrorCode.DELETE_JOB);
        }
        return DtoUtil.returnSuccess("删除成功");
    }

    /**
     * 后台文章定时任务的全部查询
     *
     * */
    @ApiOperation(value = "后台文章定时任务的全部查询", notes = "查询出所有的定时任务，使用mybatisplus的分页插件")
    @GetMapping("/joblist")
    public Dto joblist(@ApiParam(value = "当前页") @RequestParam("current") Integer current,@ApiParam(value = "页大小") @RequestParam("size") Integer size) throws Exception {
        return DtoUtil.returnDataSuccess(jobService.joblist(current, size));
    }


}
